import axios from 'axios'
export default {
	namespaced: true, //命名空间必须写
	state: {
		//是否已经登录
		hasLogin: Boolean(Object.keys(uni.getStorageSync('jo_id_token')).length),
		//用户信息/token
		infoToken: uni.getStorageSync('jo_id_token') || '',
		userInfo: uni.getStorageSync('jo_userinfo') || {},
	},
	getters: {
		userInfo(state) {
			return state.userInfo;
		},
		get_Token(state) {
			return state.infoToken;
		},
		hasLogin(state) {
			return state.hasLogin;
		}
	},
	//commit  唯一修改state值的方法	
	mutations: {
		login(state, data) { //登录成功后的操作
			console.log("mutations==login==state==>", state)
			console.log("mutations==info==data==>", data)
			//设置为已经登录
			state.hasLogin = true;
			//存储最新的用户token到本地持久化存储
			if (data.accessToken) {
				state.infoToken = data.accessToken
				uni.setStorage({
					key: 'jo_id_token',
					data: data.accessToken,
				});
				const expireTime = data.expireInSeconds * 1000 + Date.now()
				uni.setStorageSync('jo_id_token_expired', expireTime) //存入7天后时间戳
			}
			if (data.team) {
				uni.setStorage({
					key: 'jo_teaminfo',
					data: data.team,
				});
			}
		},
		userInfo(state, userInfo) {
			console.log("mutations==setUserInfo==state==>", state)
			console.log("mutations==setUserInfo==userInfo==>", userInfo)
			let _userInfo = userInfo;
			_userInfo.avatar_Small = state.baseURL + _userInfo.avatar_Small;
			_userInfo.avatar_Large = state.baseURL + _userInfo.avatar_Large;
			_userInfo.avatar_Middle = state.baseURL + _userInfo.avatar_Middle;
			//存储最新的用户数据到本地持久化存储
			state.userInfo = _userInfo;
			if (userInfo) uni.setStorageSync('jo_userinfo', _userInfo);
		},
		logout(state) {
			console.log("mutations==logout(state)==>", state);
			state.userInfo = {};
			state.infoToken = {};
			state.hasLogin = false;
			/*存入临时数据
			 *移除掉所有本地缓存
			 * 才存入临时数据存入本地
			 */
			let userName = uni.getStorageSync('jo_username')
			let TeamInfo = uni.getStorageSync('jo_teaminfo')
			let isDev = uni.getStorageSync('jo_isdev') || false
			try {
				uni.clearStorageSync();
			} catch (e) {
				// error
			}
			if (userName) uni.setStorageSync('jo_username', userName)
			if (TeamInfo) uni.setStorageSync('jo_teaminfo', TeamInfo);
			if (isDev) uni.setStorageSync('jo_isdev', isDev);
		},

	},
	//dispatch 异步的操作
	actions: {
		login() {
			context.commit('login')
		},
		setUserInfo() {
			context.commit('setUserInfo')
		},
		logout(context) {
			console.log("actions==logout(context)==>", context);
			uni.showLoading({
				mask: true
			})
			context.commit('logout')
		},
	}
}
